

package sharedServlets;

import java.io.IOException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import sessionMenegment.SessionMgr;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

import controller.Controller;

@SuppressWarnings("serial")
public class GmailLogin extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
	throws IOException {
		HttpSession session = req.getSession();
		UserService userService = UserServiceFactory.getUserService();
		//resp.sendRedirect(userService.createLoginURL(req.getRequestURI()));

		User user = userService.getCurrentUser();
		SessionMgr sessionMgr = SessionMgr.getInst();
		resp.setContentType("text/html");
		resp.getWriter().println("<h2>Log-in via google account</h2>");
		//user log in via gmail
		if (user != null) {
			System.out.println("Gmail Login: user not null");
			boolean isExist;
			String userName=user.getNickname();
			isExist = Controller.getInstance().ClientExist(userName);
			session.setAttribute("userNameClient", userName);
			session.setAttribute("googleUser", "yes");
			session.setAttribute("userEmail", user.getEmail());
			//exist user
			if(isExist){
				sessionMgr.registerUser(req.getSession(), userName,"client");
				resp.sendRedirect("allClientOrders.jsp");
			}
				
			//new user
			else{
				resp.sendRedirect("phoneRegistration.jsp");
/*				resp.getWriter().println("Welcome, " + user.getEmail());
				resp.getWriter().println("<form method=\"post\" action=\"gmailLoginPhone\">Please enter your phone number: <input type=\"text\" name=\"phoneNumber\" /><input type=\"submit\" value=\"Submit\" /></form>");
				String err = (String) session.getAttribute("error");
				if(err!=null)
					resp.getWriter().println("<font color=\"red\">"+ err +"</font><br />");
*/					
			}

			//resp.getWriter().println("Welcome, " + user.getEmail());
			resp.getWriter().println(
					"<a href='"
					+ userService.createLogoutURL(req.getRequestURI())
					+ "'> LogOut </a>");

		} else {

			resp.sendRedirect(userService.createLoginURL(req.getRequestURI()));

		}
	}
}
